<template>
  <div class="strategy-create-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>{{ isEdit ? '编辑策略' : '创建策略' }}</h2>
        </div>
      </template>
      
      <el-form :model="form" label-width="120px" :rules="rules" ref="strategyForm">
        <el-form-item label="策略名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入策略名称"></el-input>
        </el-form-item>
        
        <el-form-item label="策略描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入策略描述">
          </el-input>
        </el-form-item>
        
        <el-form-item label="选择因子" prop="factors">
          <el-select
            v-model="form.factors"
            multiple
            placeholder="请选择因子"
            style="width: 100%">
            <el-option
              v-for="factor in factors"
              :key="factor.id"
              :label="factor.name"
              :value="factor.name">
              <span>{{ factor.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ factor.category }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-divider>策略设置</el-divider>
        
        <el-form-item label="因子组合方式">
          <el-radio-group v-model="form.combinationMethod">
            <el-radio label="equal">等权重</el-radio>
            <el-radio label="custom">自定义权重</el-radio>
            <el-radio label="optimize">优化权重</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 根据选择的组合方式显示对应的设置界面 -->
        <div v-if="form.combinationMethod === 'custom'">
          <el-form-item
            v-for="(factor, index) in form.factors"
            :key="index"
            :label="factor + '权重'">
            <el-slider
              v-model="factorWeights[index]"
              :step="0.05"
              :min="0"
              :max="1"
              show-input>
            </el-slider>
          </el-form-item>
          
          <el-alert
            v-if="!isValidWeights"
            title="权重总和应为 1.0"
            type="warning"
            :closable="false"
            show-icon>
          </el-alert>
        </div>
        
        <div v-if="form.combinationMethod === 'optimize'">
          <el-form-item label="优化目标">
            <el-select v-model="form.optimizeTarget" placeholder="请选择优化目标" style="width: 100%">
              <el-option label="最大化收益" value="maxReturn"></el-option>
              <el-option label="最小化风险" value="minRisk"></el-option>
              <el-option label="最大化夏普比率" value="maxSharpe"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="回测周期">
            <el-date-picker
              v-model="form.backtestPeriod"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
        </div>
        
        <el-divider>投资标的</el-divider>
        
        <el-form-item label="基金池" prop="fundPool">
          <el-select
            v-model="form.fundPool"
            multiple
            placeholder="请选择基金池"
            style="width: 100%">
            <el-option label="全部公募基金" value="all"></el-option>
            <el-option label="股票型基金" value="stock"></el-option>
            <el-option label="混合型基金" value="mixed"></el-option>
            <el-option label="债券型基金" value="bond"></el-option>
            <el-option label="指数型基金" value="index"></el-option>
            <el-option label="自选基金" value="custom"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="form.fundPool.includes('custom')" label="自选基金">
          <el-select
            v-model="form.customFunds"
            multiple
            filterable
            placeholder="请选择自选基金"
            style="width: 100%">
            <el-option
              v-for="fund in funds"
              :key="fund.id"
              :label="fund.name"
              :value="fund.id">
              <span>{{ fund.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ fund.code }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">{{ isEdit ? '保存修改' : '创建策略' }}</el-button>
          <el-button @click="cancel">取消</el-button>
          <el-button v-if="!isEdit" type="success" @click="testStrategy">测试策略</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 策略测试结果对话框 -->
    <el-dialog
      v-model="testDialogVisible"
      title="策略测试结果"
      width="800px">
      <div class="test-result">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="策略名称">{{ form.name }}</el-descriptions-item>
          <el-descriptions-item label="测试范围">{{ form.fundPool.join(', ') }}</el-descriptions-item>
          <el-descriptions-item label="测试周期">2020-01-01 至 2025-01-01</el-descriptions-item>
          <el-descriptions-item label="测试结果">通过</el-descriptions-item>
        </el-descriptions>
        
        <div class="performance-stats">
          <h3>策略表现</h3>
          <el-table :data="performanceStats" border style="width: 100%">
            <el-table-column prop="name" label="指标" width="180"></el-table-column>
            <el-table-column prop="value" label="数值"></el-table-column>
          </el-table>
        </div>
        
        <div class="strategy-chart" style="height: 300px; margin-top: 20px;">
          <div class="chart-placeholder">
            <el-empty description="策略回测图表将在此显示"></el-empty>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="testDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm">保存策略</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'StrategyCreate',
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const strategyForm = ref(null)
    const testDialogVisible = ref(false)
    
    // 判断是否为编辑模式
    const isEdit = computed(() => {
      return route.query.mode === 'edit'
    })
    
    // 表单数据
    const form = reactive({
      id: '',
      name: '',
      description: '',
      factors: [],
      combinationMethod: 'equal',
      optimizeTarget: 'maxSharpe',
      backtestPeriod: [],
      fundPool: ['all'],
      customFunds: []
    })
    
    // 因子权重
    const factorWeights = ref([])
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入策略名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入策略描述', trigger: 'blur' }
      ],
      factors: [
        { type: 'array', required: true, message: '请至少选择一个因子', trigger: 'change' }
      ],
      fundPool: [
        { type: 'array', required: true, message: '请选择基金池', trigger: 'change' }
      ]
    }
    
    // 获取因子列表
    const factors = computed(() => {
      return store.getters.getFactors
    })
    
    // 获取基金列表
    const funds = computed(() => {
      return store.getters.getFunds
    })
    
    // 计算权重是否有效
    const isValidWeights = computed(() => {
      if (form.combinationMethod !== 'custom' || form.factors.length === 0) {
        return true
      }
      
      const sum = factorWeights.value.reduce((acc, val) => acc + val, 0)
      return Math.abs(sum - 1.0) < 0.01 // 允许0.01的误差
    })
    
    // 性能数据（模拟）
    const performanceStats = [
      { name: '年化收益率', value: '15.23%' },
      { name: '最大回撤', value: '8.76%' },
      { name: '夏普比率', value: '1.87' },
      { name: '信息比率', value: '0.92' },
      { name: '胜率', value: '62.5%' },
      { name: '年化波动率', value: '9.13%' }
    ]
    
    // 监听因子变化，初始化权重
    watch(() => form.factors, (newFactors) => {
      // 初始化每个因子的权重为平均值
      if (newFactors.length > 0) {
        const weight = 1 / newFactors.length
        factorWeights.value = newFactors.map(() => weight)
      } else {
        factorWeights.value = []
      }
    })
    
    // 生命周期钩子
    onMounted(() => {
      // 加载因子和基金数据
      store.dispatch('loadFactors')
      store.dispatch('loadFunds')
      
      // 如果是编辑模式，从store中获取策略数据
      if (isEdit.value && route.query.id) {
        const strategyId = parseInt(route.query.id)
        const strategy = store.getters.getStrategies.find(s => s.id === strategyId)
        
        if (strategy) {
          Object.keys(strategy).forEach(key => {
            if (form.hasOwnProperty(key)) {
              form[key] = strategy[key]
            }
          })
          
          // 初始化权重
          if (form.factors.length > 0) {
            const weight = 1 / form.factors.length
            factorWeights.value = form.factors.map(() => weight)
          }
        }
      }
    })
    
    // 测试策略
    const testStrategy = () => {
      if (!isValidWeights.value) {
        ElMessage.warning('请确保因子权重总和为1.0')
        return
      }
      
      // 这里实际应该调用API来测试策略
      // 模拟测试成功
      ElMessage.success('策略测试成功')
      testDialogVisible.value = true
    }
    
    // 提交表单
    const submitForm = () => {
      if (!isValidWeights.value) {
        ElMessage.warning('请确保因子权重总和为1.0')
        return
      }
      
      strategyForm.value.validate((valid) => {
        if (valid) {
          // 准备提交到后端的数据结构
          const strategyData = {
            name: form.name,
            description: form.description,
            combinationMethod: form.combinationMethod,
            optimizeTarget: form.optimizeTarget,
            fundPool: form.fundPool.join(','), // 将数组转换为字符串
            creator: '管理员'
          }
          
          if (isEdit.value) {
            // 编辑已有策略
            const strategyId = parseInt(route.query.id)
            
            store.dispatch('updateStrategy', {
              id: strategyId,
              strategy: strategyData
            }).then(() => {
              ElMessage.success('策略更新成功')
              // 关闭测试对话框（如果打开）
              testDialogVisible.value = false
              // 返回策略列表页面
              router.push('/strategy-management')
            }).catch(error => {
              ElMessage.error('更新策略失败: ' + error.message)
            })
          } else {
            // 创建新策略
            store.dispatch('addStrategy', strategyData).then((createdStrategy) => {
              ElMessage.success('策略创建成功')
              
              // 如果需要，添加因子到策略
              if (form.factors.length > 0 && createdStrategy && createdStrategy.id) {
                // 实际应用中，这里应该调用API为策略添加因子
                // 这里简化处理，只展示成功消息
                ElMessage.success('已成功添加因子到策略')
              }
              
              // 关闭测试对话框（如果打开）
              testDialogVisible.value = false
              // 返回策略列表页面
              router.push('/strategy-management')
            }).catch(error => {
              ElMessage.error('创建策略失败: ' + error.message)
            })
          }
        } else {
          return false
        }
      })
    }
    
    // 取消操作
    const cancel = () => {
      router.push('/strategy-management')
    }
    
    return {
      strategyForm,
      form,
      rules,
      testDialogVisible,
      factors,
      funds,
      factorWeights,
      isValidWeights,
      performanceStats,
      isEdit,
      testStrategy,
      submitForm,
      cancel
    }
  }
}
</script>

<style scoped>
.strategy-create-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.performance-stats {
  margin-top: 20px;
}

.chart-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: #f5f7fa;
}
</style> 